<template>
  <section class="todoapp">
    <!-- 头部部分 TodoHeader -->
    <TodoHeader @onAdd="addFn"></TodoHeader>

    <!-- 主体部分 TodoMain -->
    <TodoMain
      :list="showList"
      @onDel="delFn"
      @changeStatus="statusFn"
      @allCheck="allCheckFn"
      @onEdit="onEditFn"
    ></TodoMain>

    <!-- 底部部分 TodoFooter-->
    <TodoFooter
      @clear="clearFn"
      :list="list"
      :condition="condition"
      @onCondition="conditionFn"
    ></TodoFooter>
  </section>
</template>

<script>
// 1.组件化
import TodoHeader from "./components/TodoHeader.vue";
import TodoMain from "./components/TodoMain.vue";
import TodoFooter from "./components/TodoFooter";
export default {
  components: {
    TodoHeader,
    TodoMain,
    TodoFooter,
  },
  data() {
    return {
      /* list: [
        { id: 1, name: "吃饭", done: true },
        { id: 2, name: "睡觉", done: true },
        { id: 3, name: "打豆豆", done: false },
      ], */
      list: JSON.parse(localStorage.getItem("todos")) || [],
      /* condition: "all", */
      condition: localStorage.getItem("condition") || "all",
    };
  },
  watch: {
    list: {
      deep: true,
      handler(newVal) {
        localStorage.setItem("todos", JSON.stringify(newVal));
      },
    },
    condition(newVal) {
      localStorage.setItem("condition", newVal);
    },
  },
  methods: {
    // 删除任务
    delFn(id) {
      this.list = this.list.filter((v) => v.id !== id);
    },
    // 新增任务
    addFn(todoName) {
      this.list.unshift({
        id: Date.now(),
        name: todoName,
        done: false,
      });
    },
    // 确认框修改
    statusFn(id) {
      let todo = this.list.find((v) => v.id === id);
      todo.done = !todo.done;
    },
    // 清除已完成
    clearFn() {
      this.list = this.list.filter((v) => v.done === false);
    },
    // 全选
    allCheckFn(value) {
      this.list.forEach((v) => (v.done = value));
    },
    // 条件筛选
    conditionFn(type) {
      this.condition = type;
    },
    // 双击修改
    onEditFn(id, val) {
      let todo = this.list.find((v) => v.id === id);
      todo.name = val;
    },
  },
  computed: {
    showList() {
      if (this.condition === "active") {
        return this.list.filter((v) => !v.done);
      } else if (this.condition === "completed") {
        return this.list.filter((v) => v.done);
      } else {
        return this.list;
      }
    },
  },
};
</script>

<style></style>
